/*
 * TileTest.java
 *
 * Created on 24.10.2007, 12:14:11
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.cse.emea.map;

import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author jtrapp
 */
public class GetImageSizes {
    private static HashMap<String, Dimension> dimMap = new HashMap<String, Dimension>();

    public static void main(String[] args) {
        File dir = new File(args[1]);
        processDirectory(args[0], dir);

    }

    // This method writes a DOM document to a file
    public static void writeXmlFile(Document doc, File file) {
        try {
            // Prepare the DOM document for writing
            Source source = new DOMSource(doc);

            // Prepare the output file
            Result result = new StreamResult(file);

            // Write the DOM document to the file
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }
    }

    public static String getNodeValue(Document element, String tagname) {
        NodeList nodeList = element.getElementsByTagName(tagname);
        if (nodeList.getLength() > 0) {
            if (nodeList.item(0).getFirstChild() != null) {
                return nodeList.item(0).getFirstChild().getNodeValue();
            } else {
                return "";
            }
        }

        return "[<" + tagname + "> not found]";
    }

    public static Node getNode(Document element, String tagname) {
        NodeList nodeList = element.getElementsByTagName(tagname);
        if (nodeList.getLength() > 0) {
            return nodeList.item(0).getFirstChild();
        }
        System.out.println("not found " + tagname);
        return null;
    }

    public static Element getElement(Document element, String tagname) {
        NodeList nodeList = element.getElementsByTagName(tagname);
        if (nodeList.getLength() > 0) {
            return (Element) nodeList.item(0);
        }
        System.out.println("not found " + tagname);
        return null;
    }


    // Parses an XML file and returns a DOM document.
    // If validating is true, the contents is validated against the DTD
    // specified in the file.
    public static Document parseXmlFile(File file, boolean validating) {
        try {
            // Create a builder factory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(validating);

            // Create the builder and parse the file
            Document doc = factory.newDocumentBuilder().parse(file);
            return doc;
        } catch (SAXException e) {
        // A parsing error occurred; the xml input is not valid
        } catch (ParserConfigurationException e) {
        } catch (IOException e) {
        }
        return null;
    }

    /** Run recursivley*/
    private static int processDirectory(String root, File dir) throws DOMException {
        File[] files = dir.listFiles();
        int countKMLs = 0;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                countKMLs += processDirectory(root, files[i]);
            } else if (files[i].getName().matches(".*yab[0-9]{1,3}.kml")) {
                System.out.println("Reading image for: " + files[i].getAbsolutePath());
                Document doc = parseXmlFile(files[i], false);
                Element imageLink = getElement(doc, "imageLink");
                // This method ensures that all pixels have been loaded before returning
                if (imageLink != null) {
                    try {
                        Node imageLinkNode = imageLink.getFirstChild();
                        System.out.println("Processing: " + imageLinkNode.getNodeValue());
                        String urlString=imageLinkNode.getNodeValue();
                        java.awt.Image image;
                        if (!urlString.startsWith("http")){ //Not sure, if the complete url will be used all the time
                            urlString="http://mw1.google.com/mw-earth-vectordb/outreach/media/yab/images/"+urlString;
                        } 
                        int width = -1;
                        int height = -1;
                        if (dimMap.containsKey(urlString)){                           
                            Dimension dim = dimMap.get(urlString);
                            width = dim.width;
                            height = dim.height;
                        }
                        else {
                            URL url = new URL(urlString);
                            image = new ImageIcon(url).getImage();
                        
                        // Get the dimensions of the image; these will be non-negative
                         width = image.getWidth(null);
                         height = image.getHeight(null);
                         dimMap.put(urlString, new Dimension(width, height));
                        }
                        imageLink.setAttribute("width", width + "");
                        imageLink.setAttribute("height", height + "");
                        System.out.println("Width: " + width + "  height: " + height);
                    } catch (MalformedURLException ex) {
                        Logger.getLogger(GetImageSizes.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                writeXmlFile(doc, files[i]);
            } else {
                System.out.println("ignored file for: " + files[i].getAbsolutePath());
            }
        }
        return countKMLs;
    }
}
